//
//  BaseViewModel.m
//  CommunityCircle
//
//  Created by 毕武侠 on 16/3/5.
//  Copyright © 2016年 ssyx. All rights reserved.
//

#import "BaseViewModel.h"

@interface BaseViewModel ()

@property (nonatomic, strong, readwrite) RACSubject *errors;
@property (nonatomic, strong, readwrite) RACSubject *willDisappearSignal;

@end

@implementation BaseViewModel

- (instancetype)initWithParams:(SGParameter *)params {
    return [self initWithUrl:nil withParams:params];
}

- (instancetype)initWithUrl:(NSString *)url {
    return [self initWithUrl:url withParams:[[SGParameter alloc] init]];
}

- (instancetype)initWithUrl:(NSString *)url withParams:(SGParameter *)params {
    self = [super init];
    if (self) {
        self.url = url;
        self.params = params;
        self.shouldRequestRemoteDataOnViewDidLoad = YES;
        self.shouldFetchLocalDataOnViewModelInitialize = YES;
        
        [self initialize];
    }
    return self;
}

- (void)setUrl:(NSString *)url {
//    _url = url ? [NSString stringWithFormat:@"%@%@",[OtherNetworking sharedManager].STRURL, url] : [OtherNetworking sharedManager].STRURL;
    _url = url? Host_Append(url):@"";
}

- (RACSubject *)errors {
    if (!_errors) _errors = [RACSubject subject];
    return _errors;
}

- (RACSubject *)willDisappearSignal {
    if (!_willDisappearSignal) _willDisappearSignal = [RACSubject subject];
    return _willDisappearSignal;
}

- (RACCommand *)command {
    if (_command == nil) {
       _command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSString *class) {
           
            RACSignal *requestSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                if (self.params == nil || self.url == nil) {
                    NSError *error = [NSError errorWithDomain:@"请求参数为空" code:-100 userInfo:nil];
                    [subscriber sendError:error];
                } else {
                    [SGHttpTool POST:self.url parameter:self.params sucess:^(id result) {
                        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
                        NSString *resultStr =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
                        NSLog(@"%@",resultStr);
                        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataWord:@"question_list"  dataClass:NSClassFromString(class)];
                        NSInteger code = [receive.status intValue];
//                        if (code != 2000) {
//                            NSString *domain = receive.msg ? : @"获取数据错误！";
//                            self.msg = domain;
//                            NSError *error = [NSError errorWithDomain:domain code:code userInfo:nil];
//                            [subscriber sendError:error];
//                        } else {
                            self.msg = receive.msg;
                            [subscriber sendNext:receive.data];
                            [subscriber sendCompleted];
//                        }
                    } failure:^(id reslut) {
                        NSError *error = reslut;
                        error = [NSError errorWithDomain:error.localizedDescription code:5000 userInfo:nil];
                        [subscriber sendError:error];
                    }];
                }
                return nil;
            }];
            // 在返回数据信号时，把数据中的字典映射成模型信号，传递出去
            return requestSignal;
        }];
    }
    return _command;
}

- (void)initialize {
//    RACSignal*startedMessageSource = [self.command.executionSignals map:^id(RACSignal *subscribeSignal) {
//        return NSLocalizedString(@"Sending request...", nil);
//    }];
    
//    RACSignal*completedMessageSource = [self.command.executionSignals flattenMap:^RACStream *(RACSignal *subscribeSignal) {
//        return[[[subscribeSignal materialize] filter:^BOOL(RACEvent *event) {
//            return event.eventType == RACEventTypeCompleted;
//        }]map:^id(id value) {
//            return NSLocalizedString(@"Thanks", nil);
//        }];
//    }];
    
//    RACSignal*failedMessageSource = [[self.command.errors subscribeOn:[RACScheduler mainThreadScheduler]] map:^id(NSError *error) {
//        return error.domain;
//    }];

//    RAC(self, msg) = [RACSignal merge:@[startedMessageSource, failedMessageSource]];
//    RAC(self, msg) = [RACSignal merge:@[startedMessageSource,completedMessageSource, failedMessageSource]];
}

//- (void)initialize:(NSString *)url {
//    self.url = url ? [NSString stringWithFormat:@"%@%@",[OtherNetworking sharedManager].STRURL, url] : [OtherNetworking sharedManager].STRURL;
//    
//    self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSString *class) {
//        RACSignal *requestSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//            [SGHttpTool POST:self.url parameter:self.params sucess:^(id result) {
//                SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(class)];
//                NSInteger code = [receive.code intValue];
//                if (code != 2000) {
//                    NSString *domain = receive.msg ? : @"获取数据错误！";
//                    NSError *error = [NSError errorWithDomain:domain code:code userInfo:nil];
//                    [subscriber sendError:error];
//                } else {
//                    self.msg = receive.msg;
//                    [subscriber sendNext:receive.data];
//                    [subscriber sendCompleted];
//                }
//            } failure:^(id reslut) {
//                [subscriber sendError:reslut];
//            }];
//            return nil;
//        }];
//        // 在返回数据信号时，把数据中的字典映射成模型信号，传递出去
//        return requestSignal;
//    }];
//}


@end
